var express = require("express");
const userModel = require("../../models/usermodel");
const MD5 = require("MD5");
const jwt = require("jsonwebtoken");

var router = express.Router();

//验证登录信息
router.post("/login", (req, res, next) => {
  let { username, password } = req.body;

  userModel
    .findOne({ username: username, password: MD5(password) })
    .then((data) => {
      if (!data) {
        //记住 ：一定要加return 否则 后面的res.json也要执行，
        //导致错误(Cannot set headers after they are sent to the client)，服务停止
        return res.json({
          code: "2001",
          msg: "用户或密码错误~~~",
          data: null,
        });
      }

      let token = jwt.sign({ username: data.username }, "abcde45@#fg", {
        expiresIn: 60 * 60 * 24 * 7,
      });
      res.json({
        code: "2001",
        msg: "登录成功",
        data: token,
      });
    })
    .catch((err) => {
      res.json({
        code: "1001",
        msg: "读取失败",
        data: null,
      });
    });
});

module.exports = router;
